package com.aaa.sys.service.impl;

import com.aaa.common.constant.ConstantUtil;
import com.aaa.common.entity.User;
import com.aaa.common.util.*;
import com.aaa.common.vo.Page;
import com.aaa.sys.dao.UserDao;
import com.aaa.sys.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * 用户信息表(User)表服务实现类
 *
 * @author makejava
 * @since 2025-09-03 19:03:33
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private HttpServletRequest request;

    @Override
    public Result checkPassword(String password) {
        String userId = TokenUtil.getUserId(request);
        User user = userDao.queryById(Integer.valueOf(userId));
        String passwordDb = user.getPassword();
        String salt = user.getSalt();
        Sha512Hash oldPasswordHash = new Sha512Hash(password, salt, ConstantUtil.SHRIO_HASH_ITERATIONS);
        if (!oldPasswordHash.toString().equals(passwordDb)) {
            return BaseUtil.fail("旧密码输入错误！");
        }
        return BaseUtil.success("密码验证成功！");
    }

    @Override
    public Result updatePassword(String oldPassword, String newPassword) {
        String userId = TokenUtil.getUserId(request);
        User user = userDao.queryById(Integer.valueOf(userId));
        String passwordDb = user.getPassword();
        String salt = user.getSalt();
        Sha512Hash oldPasswordHash = new Sha512Hash(oldPassword, salt, ConstantUtil.SHRIO_HASH_ITERATIONS);
        if (!oldPasswordHash.toString().equals(passwordDb)) {
            return BaseUtil.fail("旧密码输入错误！");
        }
        String newSalt = UUID.randomUUID().toString();
        Sha512Hash newPasswordHash = new Sha512Hash(newPassword, newSalt, ConstantUtil.SHRIO_HASH_ITERATIONS);
        user.setPassword(newPasswordHash.toString());
        user.setSalt(newSalt);
        try {
            int update = userDao.update(user);
            System.out.println("=========================" + user);
            if (update > 0) {
                return BaseUtil.success("修改密码成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseUtil.fail("修改密码失败！");
        }
        return null;
    }

    @Override
    public User selectOne() {
        String userId = TokenUtil.getUserId(request);
        return userDao.queryById(Integer.valueOf(userId));

    }

    @Override
    public User queryByUserName(String username) {
        User user = new User();
        user.setUserName(username);
        user.setDelFlag("0");
        user.setStatus("0");
        List<User> users = this.userDao.queryAllByLimit(user);
        if (users != null && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer userId) {
        return this.userDao.queryById(userId);
    }

    /**
     * 分页查询
     *
     * @param page 筛选条件
     * @return 查询结果
     */
    @Override
    public PageInfo queryByPage(Page<User> page) {
        //分页操作  分页参数一定要进行传递
        if (page == null || page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0) {
            //进行业务编写时，可以抛出自定义异常
            throw new CustomException(ResultStatus.PARAM_NOT_EMPTY.getReturnCode(),
                    ResultStatus.PARAM_NOT_EMPTY.getReturnMessage());
        }
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        //获取查询对象
        User user = page.getData();
        return new PageInfo(userDao.queryAllByLimit(user));
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        String userId = TokenUtil.getUserId(request);
        User user1 = userDao.queryById(Integer.valueOf(userId));
        user.setCreateBy(user1.getUserName());
        user.setUpdateBy(user1.getUserName());
        user.setSalt(UUID.randomUUID().toString());
        Sha512Hash passwordHash = new Sha512Hash(user.getPassword(), user.getSalt(), ConstantUtil.SHRIO_HASH_ITERATIONS);
        user.setPassword(passwordHash.toString());
        user.setDelFlag("0");
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userDao.update(user);
        return this.queryById(user.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userDao.deleteById(userId) > 0;
    }
}
